<template>
  <div class="resizable-container" ref="container">
    <!-- 内容 -->
    <div class="resize-handle" @mousedown="startResize"></div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      resizing: false,
      startX: 0,
      startY: 0,
      startWidth: 0,
      startHeight: 0,
      aspectRatio: 1  // 宽高比例
    };
  },
   mounted() {
    this.aspectRatio = this.$refs.container.offsetWidth / this.$refs.container.offsetHeight;
  },
  methods: {
    startResize(event) {
      const containerRect = this.$refs.container.getBoundingClientRect();//获取可拖拽元素的大小及其相对于视口的位置
      const resizeHandleRect = event.target.getBoundingClientRect();//获取右下角元素的大小及其相对于视口的位置
      console.log(resizeHandleRect,'resizeHandleRect');
      if (event.clientX > containerRect.left + containerRect.width - resizeHandleRect.width &&
          event.clientY > containerRect.top + containerRect.height - resizeHandleRect.height) {
        this.resizing = true;
        this.startX = event.clientX;//鼠标按下时距离网页左边的距离
        this.startY = event.clientY;//鼠标按下时距离网页顶部的距离
        this.startWidth = this.$refs.container.offsetWidth;//可拖拽元素初始宽度
        this.startHeight = this.$refs.container.offsetHeight;//可拖拽元素初始高度
        document.addEventListener('mousemove', this.resize);//添加鼠标移动事件
        document.addEventListener('mouseup', this.stopResize);//添加鼠标移动松开事件
      }
    },
    resize(event) {
      if (this.resizing) {
        const width = this.startWidth + event.clientX - this.startX;//鼠标移动的X值
        const height = this.startHeight + event.clientY - this.startY;//鼠标移动的Y值
        this.$refs.container.style.width = `${width}px`;//重新设置宽度
        this.$refs.container.style.height = `${height}px`;//重新设置高度
      }
    },
    //  resize(event) {
    //   if (this.resizing) {
    //     const deltaX = event.clientX - this.startX;
    //     const deltaY = event.clientY - this.startY;

    //     if (Math.abs(deltaX) > Math.abs(deltaY)) {
    //       // 水平方向移动更多，以水平方向为准
    //       this.$refs.container.style.width = `${this.startWidth + deltaX}px`;
    //       this.$refs.container.style.height = `${(this.startWidth + deltaX) / this.aspectRatio}px`;
    //     } else {
    //       // 垂直方向移动更多，以垂直方向为准
    //       this.$refs.container.style.height = `${this.startHeight + deltaY}px`;
    //       this.$refs.container.style.width = `${(this.startHeight + deltaY) * this.aspectRatio}px`;
    //     }
    //   }
    // },
    stopResize() {
      this.resizing = false;
      document.removeEventListener('mousemove', this.resize);//鼠标松开移除事件
      document.removeEventListener('mouseup', this.stopResize);//鼠标松开移除事件
    }
  }
};
</script>

<style>
.resizable-container {
  position: absolute;
  border: 1px solid #ccc;
  overflow: hidden;
  width: 200px;
  height: 200px;
}

.resize-handle {
  position: absolute;
  width: 10px;
  height: 10px;
  background-color: #ccc;
  cursor: nwse-resize;
  bottom: 0;
  right: 0;
}
</style>